package com.tree.xinhe.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.tree.xinhe.CallBack;
import com.tree.xinhe.R;
import com.tree.xinhe.adapter.ViewPagerAdapter;
import com.tree.xinhe.entity.AdImg;
import com.tree.xinhe.util.RequestUtil;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

/**
 * Created by tree on 2016/12/29.
 */

public class HeadFragment extends Fragment implements CallBack{

    private Context ctx;
    private ViewPager viewPager;
    private RadioGroup group;

    private RequestUtil util;
    private List<AdImg> imgList = new ArrayList<>();
    private List<ImageView> ilist;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.ctx = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_head,null,false);
        initViews(view);
        getDataByNet();
        initRadioButton();
        bintEvent();
        handler.postDelayed(new TimerRunnable(), ROLL_TIME);
        return view;
    }

    private void initViews(View view) {
        viewPager = (ViewPager) view.findViewById(R.id.viewPager);
        group = (RadioGroup) view.findViewById(R.id.group);
    }

    /**
     * 初始化radiobutton
     */
    private void initRadioButton(){
        for (int i=0;i<4;i++){
            RadioButton radioButton = (RadioButton)LayoutInflater.from(ctx).inflate(R.layout.head_radiobutton,null,false);
            radioButton.setId(i);
            RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.setMargins(8, 0, 8, 0);
            group.addView(radioButton,lp);
        }
        ((RadioButton)group.getChildAt(0)).setChecked(true);
    }

    /**
     * 初始化viewPager
     */
    private void initViewPager(){
        ilist = new ArrayList<>();
        //准备要显示的数据
        for (AdImg ad:imgList){
            ImageView imageView = new ImageView(ctx);
//            Log.w("tree",ad.getImgUrl()+"=====");
            String imgurl = "http://120.27.97.93:8080/xhsc"+ad.getImgUrl();
            Glide.with(ctx).load(imgurl).into(imageView);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            ilist.add(imageView);
        }
        //定义适配器
        PagerAdapter adapter = new ViewPagerAdapter(ilist);
        //关联适配器
        viewPager.setAdapter(adapter);
        //设置ViewPager的默认项, 设置为长度的100倍，这样子开始就能往左滑动  或者Integer.MAX_VALUE/2
        viewPager.setCurrentItem((imgList.size())*100);
    }

    /**
     * 联动
     */
    private void bintEvent(){
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if(position%4==0){
                    ((RadioButton)group.getChildAt(0)).setChecked(true);
                } else if(position%4==1){
                    ((RadioButton)group.getChildAt(1)).setChecked(true);
                } else if(position%4==2){
                    ((RadioButton)group.getChildAt(2)).setChecked(true);
                } else if(position%4==3){
                    ((RadioButton)group.getChildAt(3)).setChecked(true);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private Handler handler = new Handler();
    //轮播间隔时间
    private static final int ROLL_TIME = 5000;



    /**
     * 实现viewPager自动轮播（每两秒执行一次，第一个2秒是new TimerRunnable(),执行第一次换图片）
     */
    class TimerRunnable implements Runnable {

        @Override
        public void run() {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);//换到下一张
            if (handler != null) {
                //如果hander还存在 ，就继续执行切换图片，实现轮播
                handler.postDelayed(this, ROLL_TIME);
            }
        }
    }



    private void getDataByNet(){
        util = new RequestUtil(ctx,this);
        util.getData(getMap());
    }

    private Map<String,String> getMap(){
        Map<String,String> map = new Hashtable<>();
        map.put("isTop","1");
        return map;
    }

    @Override
    public void callback(String json) {
//        Log.w("tree","====="+json);
        imgList.clear();
        imgList.addAll(JSON.parseArray(json,AdImg.class));
        initViewPager();
    }

    @Override
    public void errorCallback(VolleyError volleyError) {
        Log.w("tree","这是接受广告图片的错误信息"+volleyError.toString());

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler = null; //此处在Activity退出时及时 回收
    }
}
